%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% O-Ring Production Networks
%   Author: Demir, Fieler, Xu, Yang
%   Last updated: January 2021
%
% Purpose: Export Shock Counterfactual Analysis (Full Model)
%   - Resolve initial equilibrium
%   - Counterfactual 1: baseline counterfactual
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
close all; diary off; clc; clear; 

    
%% Resolve Initial Equilibrium
fprintf('\nInitial Equilibrium\n');

    % parameters
    define_param

    % add estiamted parameters 
    load('../../output/estimates/fullmodel_estimates.mat', 'est');            
    define_param_est %add estiamted parameters     

    % data moment
    define_data_moment
    
    % constants
    define_omega_dist %firm type and density
    define_const %qgrid, phi_v, phy_y, D_F and other constants
    
    % solve initial equilibrium
    eqm = solve_eqm_outer(param, const);    
    define_wage_schedule %add wage schedule
    
    % calculate model moments
    model = cal_model_moment(param, const, eqm); 
    
    % calculate vars for each firm type
    firm = cal_firm_vars(param, const, eqm);
   
  

    
%% 5 Percent Export Demand Shock

    const.D_F = param.shock*const.D_F;
    
    
    
%% Counterfactual #1: Baseline Counterfactual 
fprintf('\nBaseline Counterfactual\n');

    % solve the equilibrium
    eqm_cf1 = solve_eqm_cf1_outer(param, const, eqm);
    
    % calculate vars for each firm type    
    firm_cf1 = cal_firm_vars(param, const, eqm_cf1);
    
    % counterfactual changes
    ge_cf1 = cal_chg_ge(eqm, firm, eqm_cf1, firm_cf1);       
    


%% Output tables and figures
diary off

    % create folder
    mkdir('../../output/figures') 
    mkdir('../../output/tables') 
   
    % output results
    out_baselinecf_figures
    out_baselinecf_tables
    
    
